package com.antony.message0928_2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class Sever implements Runnable {
	private ArrayList<Message> msg;
	private Socket sk;
	private Message m = new Message();
	private int count;

	public Sever(ArrayList<Message> msg, Socket sk,int count) {
		this.msg = msg;
		this.sk = sk;
		this.count = count;
	}

	public void run() {
        recieve();
	}

	public void recieve() {
		try {
			while (true) {
				OutputStream out;
				BufferedReader bs;
				InputStream in;
                
				String wel = "welcome!Please enter your username:\n\t";
				out = sk.getOutputStream();
				in = sk.getInputStream();
				out.write(wel.getBytes());
				bs = new BufferedReader(new InputStreamReader(in));
				String name = bs.readLine();
				m.setName(name);
				msg.add(count,m);
				out.write(("Your username is:" + name + "\n\t").getBytes());
				Together tr = new Together(out, msg);
				Thread td = new Thread(tr);
				td.start();
				while (msg.get(count).getStart()) {
					bs = new BufferedReader(new InputStreamReader(in));
					msg.get(count).addMsg(" said:"+bs.readLine()+"\n\t");
				//	out.write((name + "said:" + bs.readLine() + "\n\t").getBytes());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
